from fastapi import FastAPI, Request, Form
from fastapi.staticfiles import StaticFiles
from fastapi.templating import Jinja2Templates
import datetime
import os
import requests
import time
from apscheduler.schedulers.background import BackgroundScheduler
scheduler = BackgroundScheduler()

app = FastAPI()

# 配置模板路径
templates = Jinja2Templates(directory="templates")
# 配置静态文件
app.mount("/static", StaticFiles(directory="static"), name="static")


def  init_Authorization(Authorization):
    file_path = os.path.join(os.path.dirname(__file__), "Authorization.txt")
    if Authorization ==""  and not os.path.exists(file_path):
        Authorization="iZiTsAB82dgaYPIek6lASgUTwEAAoelAJ/VMiy8R8l84sosJO4IhM7adSWDfEmyQPnTWCyITKzkIf+bct1qCIun6zyxWaKJ6ot0VP8PaTWKfFRvX8f8mXitBCloxcPHyeZkpqy2GJG3cY4CbJb2Mtw+miI5nNhlcRhaesM9NWIsalijW/57YaFRvKr9Ak0seJHSaihVUjP6BVisYOn2b2EDWd5o1fPxDrnVEojCXBOg+/ZQw4pC/wQ=="

    if not os.path.exists(file_path) or Authorization!= "":
        with open(file_path, "w") as f:
            f.write(Authorization)

    with open(file_path, "r") as f:
        Authorization = f.read()
    return Authorization


def parse_趋势(data_str):
    """
    判断传递进来的data_str是整数还是字符串，如果是整数，那么大于0，则返回上升，否则返回下降，如果是字符串，则判断字符串是否包含-，如果包含，则返回上升，否则返回下降

    :param data:
    :return:
    """
    str_josin=""
    if isinstance(data_str, int) or isinstance(data_str, float):
        if data_str > 0:
            str_josin= "上升"
        else:
            str_josin=  "下降"
        data_str=f"{data_str}"
    else:
        if "-" in data_str:
            str_josin=  "上升"
        else:
            str_josin=  "下降"
    data_str=data_str.replace("-","")
    return f"{str_josin}{data_str}"
def get_requests(KSSJ_time, JSSJ_time,yzm,PX="DESC"):
    """
    :param KSSJ_time:
    :param JSSJ_time:
    :param yzm: 查询参数 PM10 PM25
    :return:
    """
    if yzm  in [ "PM25", "PM10"]:
        PX="ASC"
    url = "https://119.36.187.45:9001/emdc/mobile/CityCustomAir.jsp"
    querystring = {"areaType": "HBS", "timeType": "custom", "PX": PX, "PXM": yzm, "KSSJ": KSSJ_time,
                   "JSSJ": JSSJ_time, "yzm": yzm}
    payload = ""
    headers = {
        "Authorization": init_Authorization(""),
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate, br",
        "User-Agent": "PostmanRuntime-ApipostRuntime/1.1.0",
        "Connection": "keep-alive"
    }
    max_retries = 3  # 最大重试次数
    retry_delay = 2  # 每次重试的延迟时间（秒）
    for attempt in range(max_retries):
        try:


            response = requests.request("GET", url, data=payload, headers=headers, params=querystring, verify=False,proxies={"http":None,"https":None},timeout=60)
            if response.status_code!= 200:
                raise Exception(f"请求{yzm}失败{response.status_code}")

            rspjson = response.json()
            if rspjson['status']!= "000":
                raise Exception(f"请求{yzm}失败{rspjson['status']}")

            rspjson_data = rspjson["data"]
            for i in rspjson_data:
                if i['SSXZQ'] == "应城市":
                    rsp_json_应城=i
                    return rsp_json_应城
            raise Exception(f"找不到应城市{yzm}数据{rspjson['status']}")

        except Exception as e:
            print(f"错误: {e}. {attempt + 1} / {max_retries} 尝试中...")
            time.sleep(retry_delay)  # 等待一段时间再重试
    raise Exception("达到最大重试次数，操作失败。")
@app.get("/")
async def root(request: Request):

    #2024-01-01 获取这个格式的时间
    # 获取今年的1月1日
    current_year = datetime.datetime.now().year
    KSSJ_time = datetime.datetime(current_year, 1, 1).strftime("%Y-%m-%d")
    JSSJ_time = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    Authorization=init_Authorization("")
    message = get_message(KSSJ_time, JSSJ_time)
    return templates.TemplateResponse("html.html", {"request": request,"KSSJ_time":KSSJ_time,"JSSJ_time":JSSJ_time,"Authorization":Authorization,"message":message})




def format_date_string(date_str: str) -> str:
    """将字符串格式的日期 'YYYY-MM-DD' 转换为 'YYYY年MM月DD日' 形式"""
    # 将字符串转换为 datetime 对象
    date = datetime.datetime.strptime(date_str, "%Y-%m-%d")
    # 格式化为 'YYYY年MM月DD日' 形式
    return date.strftime("%Y年%m月%d日")

def get_message(start_time, end_time):
    end_time_str = format_date_string(end_time)
    优良率_data = get_requests(start_time, end_time, "YLL")
    优良率_data_Messagetext = f"优良天数比例为{优良率_data['YLL']}%，同比去年{parse_趋势(优良率_data['TB'])}%。在全省113个县域城市排名为{优良率_data['PM']}名，{parse_趋势(优良率_data['GSPM'])}位。"
    PM25_data = get_requests(start_time, end_time, "PM25")
    PM25_data_Messagetext = f"PM2.5为{PM25_data['PM25']}微克/立方米，同比去年{parse_趋势(PM25_data['TB'])}%，在全省113个县域城市排名为{PM25_data['PM']}名，{parse_趋势(PM25_data['GSPM'])}位。"
    PM10_data = get_requests(start_time, end_time, "PM10")
    PM10_data_Messagetext = f"PM10为{PM10_data['PM10']}微克/立方米，同比去年{parse_趋势(PM10_data['TB'])}%，在全省113个县域城市排名为{PM10_data['PM']}名，{parse_趋势(PM10_data['GSPM'])}位。"
    message = f"""截至{end_time_str}，应城市{优良率_data_Messagetext}{PM25_data_Messagetext}{PM10_data_Messagetext}"""
    return message
@app.post("/data")
async def Data(tijiaotime: str = Form(...), Authorization: str = Form(...),):
    try:
        if tijiaotime == "" :
            return {"message": "参数搞错了，自己去重新选"}
        times=tijiaotime.split(" - ")
        start_time=times[0].strip()
        end_time=times[1].strip()



        if Authorization != init_Authorization(""):
            init_Authorization(Authorization)

        message = get_message(start_time, end_time)
        return {"message": message,"code":200}

    except Exception as e:
        return {"message": str(e),"code":500}


def send_messag(message):
    url = "https://open.feishu.cn/open-apis/bot/v2/hook/c08e10e2-5a3c-45aa-9016-1249ca1ec6d2"
    payload = {
        "msg_type": "text",
        "content": {"text": message}
    }
    headers = {
        "Accept": "*/*",
        "Accept-Encoding": "gzip, deflate, br",
        "User-Agent": "PostmanRuntime-ApipostRuntime/1.1.0",
        "Connection": "keep-alive",
        "Content-Type": "application/json"
    }
    response = requests.request("POST", url, json=payload, headers=headers)
    print(response.text)


def timed_job():
    print("This job is run every minute.")
    current_year = datetime.datetime.now().year
    KSSJ_time = datetime.datetime(current_year, 1, 1).strftime("%Y-%m-%d")
    JSSJ_time = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    message = get_message(KSSJ_time, JSSJ_time)
    send_messag(message)
    print(message,"This job is run every minute.")
    return message

def timed_job_v2():
    print("This job is run every minute.")
    current_year = datetime.datetime.now().year
    KSSJ_time = datetime.datetime(current_year, 1, 1).strftime("%Y-%m-%d")
    JSSJ_time = (datetime.datetime.now() - datetime.timedelta(days=1)).strftime("%Y-%m-%d")
    message = get_message(KSSJ_time, JSSJ_time)
    print(message,"This job is run every minute.")
    return message

# 定义定时任务
scheduler.add_job(timed_job, 'cron', hour=1, minute=0)
scheduler.add_job(timed_job_v2, 'interval',  minutes =5)
scheduler.start()

if __name__ == "__main__":
    import uvicorn
    uvicorn.run(app, host="0.0.0.0", port=8000)
